import 'package:get/get.dart';
import '../../function/state/user_state.dart';
import '../../function/state/single_chat_state.dart';
import '../../function/state/single_chat_message_state.dart';

import '../../function/model/single_chat_model.dart';
import '../../function/model/user_model.dart';

/// 聊天页面逻辑控制器
/// 使用GetX进行页面逻辑分离
class MessagingPageController extends GetxController {
  final UserState _userState = Get.find<UserState>();
  final SingleChatState _singleChatState = Get.find<SingleChatState>();
  final SingleChatMessageState _singleChatMessageState =
      Get.find<SingleChatMessageState>();

  final RxString pageTitle = 'Messages'.obs;

  @override
  void onInit() {
    super.onInit();
    // 初始化聊天页面数据
    _initializePageData();
  }

  /// 初始化页面数据
  void _initializePageData() {
    if (_userState.isLoggedIn && _userState.currentUser != null) {
      final userId = _userState.currentUser!.id;
      _singleChatState.setCurrentUserId(userId);
      _singleChatMessageState.setCurrentUserId(userId);
    }
  }

  bool get isLoggedIn => _userState.isLoggedIn;

  String get currentUsername =>
      _userState.currentUser?.nickname ??
      _userState.currentUser?.username ??
      '';

  String get currentAvatar =>
      _userState.currentUser?.avatar ?? 'assets/images/avatar1.png';

  List<SingleChatModel> get chats =>
      isLoggedIn ? _singleChatState.myChats : <SingleChatModel>[];

  int get totalUnread => _singleChatMessageState.totalUnreadCount;

  /// 清除所有未读（将所有对话的对方消息标记为已读）
  void clearAllUnread() {
    if (!isLoggedIn) return;
    for (final chat in chats) {
      _singleChatMessageState.markChatMessagesAsRead(chat.id);
    }
    update();
  }

  /// 获取指定聊天的未读数
  int getUnreadForChat(String chatId) {
    return _singleChatMessageState.getChatUnreadCount(chatId);
  }

  String? _initedForUserId;

  /// 确保为当前登录用户完成状态初始化（避免重复）
  void ensureInitedFor(String userId) {
    if (_initedForUserId == userId) return;
    _initedForUserId = userId;
    _singleChatState.setCurrentUserId(userId);
    _singleChatMessageState.setCurrentUserId(userId);
    update();
  }

  /// 获取对端用户信息
  UserModel? getOtherUser(SingleChatModel chat) {
    final otherId = chat.getOtherUserId(_singleChatState.currentUserId);
    if (otherId == null || otherId.isEmpty) return null;
    return _userState.getUserById(otherId);
  }

  /// 获取对端头像
  String getOtherAvatar(SingleChatModel chat) {
    return getOtherUser(chat)?.avatar ?? 'assets/images/avatar1.png';
  }

  /// 获取对端展示名（昵称优先）
  String getOtherDisplayName(SingleChatModel chat) {
    final user = getOtherUser(chat);
    if (user == null) return 'Unknown';
    return user.nickname.isNotEmpty ? user.nickname : user.username;
  }

  /// 格式化时间（显示 HH:mm）
  String formatTime(DateTime? time) {
    if (time == null) return '';
    final h = time.hour.toString().padLeft(2, '0');
    final m = time.minute.toString().padLeft(2, '0');
    return '$h:$m';
  }
}
